package org.wsiz.vro.web.flow;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.webflow.engine.FlowExecutionExceptionHandler;
import org.springframework.webflow.engine.RequestControlContext;
import org.springframework.webflow.engine.Transition;
import org.springframework.webflow.engine.support.DefaultTargetStateResolver;
import org.springframework.webflow.execution.FlowExecutionException;

import org.wsiz.vro.web.util.MessageUtil;

@Service
public class SimpleExceptionHandler implements FlowExecutionExceptionHandler {

    @Autowired
    private MessageUtil messageUtil;

    /**
     * {@inheritDoc}
     */
    public void handle(final FlowExecutionException exception, final RequestControlContext context) {
        if (context.getExternalContext().isAjaxRequest()) {
            // Let's stay in the current state as redirect is problematic with ajax.
            String msg = (exception.getCause() != null ? exception.getCause() : exception).getMessage();
            messageUtil.error("status_exception_ko", msg);
            context.execute(new Transition(new DefaultTargetStateResolver(exception.getStateId())));
        } else {
            // Let's abort and transition to the "error" view-state
            context.execute(new Transition(new DefaultTargetStateResolver("error")));
        }
    }

    /**
     * {@inheritDoc}
     */
    public boolean canHandle(final FlowExecutionException exception) {
        return true;
    }
}